package com.zzl.admin.common;

import org.apache.commons.lang3.time.DateUtils;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description：自定义日期属性编辑器
 * Created by 朱正磊 on 2019-03-22 14:26
 */
@SuppressWarnings("ALL")
public class DateEditor extends PropertyEditorSupport {

    private final boolean emptyAsNull;

    private final String dateFormat;

    private static final String[] DATE_PATTERNS = { "yyyy", "yyyy-MM", "yyyyMM", "yyyy/MM", "yyyy-MM-dd", "yyyyMMdd",
            "yyyy/MM/dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss", "yyyy/MM/dd HH:mm:ss" };

    public DateEditor(boolean emptyAsNull) {
        this.emptyAsNull = emptyAsNull;
        this.dateFormat = "yyyy-MM-dd HH:mm:ss";
    }

    public DateEditor(boolean emptyAsNull, String dateFormat) {
        this.emptyAsNull = emptyAsNull;
        this.dateFormat = dateFormat;
    }

    /**
     * description：获取格式化后的日期字符串
     * user 朱正磊
     * time 2019-03-22 14:51
     * @return 返回格式化后的日期字符串
     */
    @Override
    public String getAsText() {
        Date date = (Date) getValue();
        return date != null ? new SimpleDateFormat(this.dateFormat).format(date) : "";
    }

    /**
     * description：格式化日期字符串
     * user 朱正磊
     * time 2019-03-22 14:52
     * @param text 日期字符串
     */
    @Override
    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            String str = text.trim();
            if ((this.emptyAsNull) && ("".equals(str))) {
                setValue(null);
            } else {
                try {
                    setValue(DateUtils.parseDate(str, DATE_PATTERNS));
                } catch (ParseException e) {
                    setValue(null);
                }
            }
        }
    }

}
